w<script>
import { textFormat, } from 'vue-text-format';
import { excelAddressToRowCol, getCellTypeByValue, isNumeric} from './utils';
import Enums from "./enums"
import JTableCommonCellType from './JTableCommonCellType.vue';
export default {
    extends: JTableCommonCellType,
    data() {
        return {
            isCtrlDown:false
        };
    },
    inject:['EditEnded'],
    render(h) {
        const content = this.renderContent(h);
        this.cell.tag.inst = content.context;
        return h(
            "td",
            {
                class: "jtable-td",
                style: this.getBackgroundStyle(),
            },
            [
                content,
                this.getTextTag(this.cell,h)
            ]
        );
    },
    methods: {
        renderContent(h){  
            if(this.helper.getEdittingCell() === this.cell){
                return this.renderEditContent(h);
            }else{
                return this.renderViewContent(h);
            }
        },
        renderEditContent(h){
            this.$nextTick(()=>{
                if(this.$refs.editInput){
                    const textarea = this.$refs.editInput;
                    textarea.focus();
                    textarea.selectionStart = textarea.selectionEnd = textarea.value.length;
                }
            })
            return h(
                'textarea',
                {
                    ref:"editInput",
                    class: ["jtable-td-content","jtable-td-textarea"],
                    style: this.getCellStyle(),
                    on:{
                        keydown:(event)=>{
                            const textarea = this.$refs.editInput;
                            if (event.key === 'Escape') {
                                event.preventDefault()
                                textarea.value = this.getEditCellValue(this.cell)
                                textarea.blur()
                            }else if(event.key === 'Enter'){
                                event.preventDefault();
                                if(event.ctrlKey){//ctrl+enter 回车
                                    textarea.value = textarea.value +'\n';
                                }else{//直接enter完成编辑
                                    textarea.blur();
                                }
                            }
                        },
                        focusout:(event)=>{
                            const newVal = this.$refs.editInput.value;
                            this.helper.setEdittingCell(null);
                            this.EditEnded(this.cell, newVal, this.getEditCellValue(this.cell));
                            this.updateEditCellValue(this.cell,newVal);
                        }
                    }
                },this.getEditCellValue(this.cell)
            )
        },
        renderViewContent(h){
            return h(
                "div",
                {
                    class: ["jtable-td-content", this.isCtrlDown?"ctrl-active":''],
                    style: this.getCellStyle(),
                    backgroundColor:'none',
                    on:{
                        mousedown:(event)=>{
                            if(event.ctrlKey)
                            {
                                this.updateFocusonCellValue(this.cell.address);
                                event.preventDefault()
                            }else{
                                const [row,col] = excelAddressToRowCol(this.cell.address);
                                this.helper.selection = [row,col,row,col];
                            }
                        },
                        mousemove:(event)=>{
                            if(event.ctrlKey)
                            {
                                this.isCtrlDown = true;
                            }else{
                                this.isCtrlDown = false;
                            }
                        },
                    }
                },[
                    this.getCellDisplayDom(this.cell, h),
                ],
            )
        },
        //获得显示的内容
        getCellDisplayDom(cell, h) {
            if (!cell || !cell.type || cell.type === Enums.ValueType.Null) 
            {
                return "";
            }
            if(cell.type === Enums.ValueType.String)
            {
                let value = cell.value;
                if(value && value.length>=1 && value[0]=="'"){
                    value = value.substring(1);
                }
                if(cell.style && cell.style.numFmt){
                    return h('div',{domProps:{innerHTML:textFormat(value,cell.style.numFmt)}})
                }
                return value;
            }else if(cell.type === Enums.ValueType.Number){
                if(cell.style && cell.style.numFmt){
                    return h('div',{domProps:{innerHTML:textFormat(cell.value,cell.style.numFmt)}})
                }
                return cell.value;
            }
            else if(cell.type === Enums.ValueType.Formula || cell.formula)
            {
                return cell.formula || cell.value.formula;
            }else if (cell.type === Enums.ValueType.RichText && cell.value && cell.value.richText) {
                const richText = cell.value.richText;
                return richText.map((part) => {
                    return h("span", {
                        style: this.helper.getRichTextStyle(part)
                    }, part.text);
                });
            }else{
                return cell.value
            }
        },
        getTextTag(cell,h){
            if(cell && cell.type=== Enums.ValueType.String && isNumeric(cell.value)){
                return h('div',{
                    class:'text-tag'
                })
            }else{
                return null;
            }
        },
        //获得编辑状态的值
        getEditCellValue(cell){
            if (!cell || !cell.type || cell.type === Enums.ValueType.Null) 
            {
                return "";
            }
            if(cell.type === Enums.ValueType.String)
            {
                if(isNumeric(cell.value) && (!cell.style || cell.style.numFmt!="@")){
                    return "'"+cell.value
                }else{
                    return cell.value
                }
            }else if(cell.type === Enums.ValueType.Formula || cell.formula)
            {
                return '='+cell.formula || cell.value.formula;
            }else if (cell.type === Enums.ValueType.RichText && cell.value && cell.value.richText) {
                const richText = cell.value.richText;
                return richText.map((part) => part.text).reduce((a,b)=>a+b+"","")
            }else{
                return cell.value
            }
        },
        //将编辑框的值转化为excel单元格的值 
        updateEditCellValue(cell,value){
            if(cell.style && cell.style.numFmt == "@"){
                return value;
            }
            if(isNumeric(value))
            {
                value = Number(value.trim())
            }else if(value.length>1 && value[0] === '='){
                value = {formula:value.substring(1), result:''}
                cell.formula = value.formula;
                cell.result = '';
            }else if(value.length>1 && value[0] === "'" && isNumeric(value.substring(1))){
                value = value.substring(1);
            }
            const type = getCellTypeByValue(value);
            cell.type = type;
            cell.value = value;
            console.log('value,type,cell',value,type,cell)
        },
        getCellStyle()
        {
            return this.helper.getStyle(this.cell.style,true,true,false);
        },
        getBackgroundStyle(){
            let style = this.helper.getStyle(this.cell.style,false,false,true);
            style.backgroundColor = style.backgroundColor == 'none'?'white':style.backgroundColor;
            return style;
        },
        updateFocusonCellValue(text){
            const activeEl = document.activeElement;
            if(activeEl&& (activeEl.tagName === 'INPUT' ||
                activeEl.tagName === 'TEXTAREA' ||
                activeEl.isContentEditable))
            {
                const start = activeEl.selectionStart
                const end = activeEl.selectionEnd
                let value = activeEl.value || activeEl.innerText
                if(value.length<1 || value[0]!=='=')
                {
                    return;
                }
                // 插入文本（替换选中部分）
                const newValue = value.substring(0, start) + text + value.substring(end)
                if (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA') {
                    activeEl.value = newValue
                    // 触发 input 事件，让 v-model 生效
                    activeEl.dispatchEvent(new Event('input', { bubbles: true }))
                } else if (activeEl.isContentEditable) {
                    activeEl.innerText = newValue
                    activeEl.dispatchEvent(new Event('input', { bubbles: true }))
                }
                // 可选：将光标移到插入文本之后
                const newCursorPos = start + text.length
                activeEl.setSelectionRange?.(newCursorPos, newCursorPos)
                activeEl.focus()
            }
        },
    },
};
</script>

<style>
.jtable-td {
    box-sizing: border-box;
    margin: 0;
    height: 100%;
    position: relative;
}
.jtable-td-content {
    position: absolute;
    top: 0;
    left: 2px;
    right: 2px;
    bottom: 0;
    overflow: hidden;
    box-sizing: border-box;
    white-space: nowrap;
    display: flex;
}
.ctrl-active{
    cursor: cell;
}
.jtable-td-textarea{
    z-index: 999;
    resize: none;
    border: none;
    background: none;
}
.jtable-td-textarea:focus{
    border: none;
    outline: none;
    background: none;
}
.text-tag{
    position: absolute;
    top:0px;
    left:0px;
    border-left: 4px solid var(--theme-select-color,#109968); /* 左侧透明 */
    border-right: 4px solid transparent; /* 右侧透明 */
    border-bottom: 4px solid transparent; /* 底部黑色，形成三角形 */
}
</style>
